<script setup>
import { ref, computed, watch, watchEffect } from 'vue'
import BaseRankingChart from '@/components/chart/BaseRankingChart.vue'
import BasePieChart from '@/components/chart/BasePieChart.vue'
import BaseChart from '@/components/chart/BaseChart.vue'
import CustomDatePicker from '@/components/header/CustomDatePicker.vue'
import { useAreaStore } from '@/stores/area'
import { useCompanyStore } from '@/stores/company'
import dayjs from 'dayjs'
import { getAllAreaReportApi, getAreaReportApi } from '@/api/area'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { handleError } from '@/utils/handleError'
import { generateTimeConfig } from '@/utils/date'
import { useMobileDetection } from '@/composables/useMobileDetection'
let areaStore = useAreaStore()
let companyStore = useCompanyStore()
const selectedArea = ref(null)

// 添加加载状态
const pieChartLoading = ref(false)
const rankingChartLoading = ref(false)
const trendChartLoading = ref(false)
const tableLoading = ref(false)



// 饼图数据和时间控制
const pieChartTime = ref(null)
const PieChartData = ref([])

// 排名图数据和时间控制
const rankingChartTime = ref(null)
const RankingChartData = ref([])

// 趋势图数据和时间控制
const chartData = ref([])
const chartTimeRange = ref(null)

// 表格相关
const tableRef = ref(null)

// 添加空值检查
const tableTimeConfig = generateTimeConfig('monthly', 0) || { start_time: 0, end_time: 0 }
let tableDataRange = ref([
  tableTimeConfig.start_time,  // 月初
  tableTimeConfig.end_time     // 月末或今天的时间(根据generateTimeConfig的逻辑)
])
const areaData = ref([])

// 端类型检测统一
const { isMobile, isTablet, isPC } = useMobileDetection();
const rankingHorizontal = computed(() => isPC.value);

// 获取区域总数据的通用方法
async function getAreaTotalData(start_time, end_time, interval = '') {
  if (!start_time || !end_time) return null

  // 添加公司检查
  if (!companyStore.currentCompany || !companyStore.currentCompany.id) {
    console.warn('当前公司信息不存在');
    return null;
  }

  try {
    let res = await getAllAreaReportApi({
      id: companyStore.currentCompany.id,
      start_time,
      end_time,
      interval,
      type: 2,
    })

    // 添加返回值检查
    if (!res || !res.aggregated_data) {
      console.warn('获取区域数据返回格式不正确:', res);
      return null;
    }

    return res.aggregated_data
  } catch (error) {
    handleError(error, '获取区域数据失败')
    return null
  }
}

// 监听饼图时间变化
watchEffect(async () => {
  if (pieChartTime.value) {
    pieChartLoading.value = true
    try {
      let data = await getAreaTotalData(pieChartTime.value.start_time, pieChartTime.value.end_time)
      if (data) {
        // 添加检查确保data可以被flat
        if (!Array.isArray(data)) {
          console.warn('饼图数据格式不正确, 期望数组但收到:', typeof data);
          PieChartData.value = [];
          return;
        }

        PieChartData.value = data.flat()
          .map(item => {
            // 添加项目级空值检查
            if (!item || typeof item.area_id === 'undefined' || typeof item.usage === 'undefined') {
              console.warn('饼图数据项格式不正确:', item);
              return null;
            }

            return {
              name: areaStore.getAreaNameById(item.area_id) || `区域${item.area_id}`,
              value: Number(item.usage) || 0,
              area_id: item.area_id
            };
          })
          .filter(item => item !== null && item.value > 0)
          .sort((a, b) => b.value - a.value)
      } else {
        PieChartData.value = []
      }
    } catch (error) {
      handleError(error, '获取饼图数据失败')
      PieChartData.value = []
    } finally {
      pieChartLoading.value = false
    }
  }
})

// 监听排名图时间变化
watchEffect(async () => {
  if (rankingChartTime.value) {
    rankingChartLoading.value = true
    try {
      let data = await getAreaTotalData(rankingChartTime.value.start_time, rankingChartTime.value.end_time)
      if (data) {
        // 添加检查确保data可以被flat
        if (!Array.isArray(data)) {
          console.warn('排名图数据格式不正确, 期望数组但收到:', typeof data);
          RankingChartData.value = [];
          return;
        }

        RankingChartData.value = data.flat()
          .map(item => {
            // 添加项目级空值检查
            if (!item || typeof item.area_id === 'undefined' || typeof item.usage === 'undefined') {
              console.warn('排名图数据项格式不正确:', item);
              return null;
            }

            return {
              name: areaStore.getAreaNameById(item.area_id) || `区域${item.area_id}`,
              value: Number(item.usage) || 0,
              area_id: item.area_id
            };
          })
          .filter(item => item !== null)
          .sort((a, b) => b.value - a.value)
      } else {
        RankingChartData.value = []
      }
    } catch (error) {
      handleError(error, '获取排名数据失败')
      RankingChartData.value = []
    } finally {
      rankingChartLoading.value = false
    }
  }
})

// 获取单个区域趋势数据
async function getAreaData() {
  if (!selectedArea.value || !chartTimeRange.value) return
  trendChartLoading.value = true
  try {
    let res = await getAreaReportApi({
      id: selectedArea.value,
      ...chartTimeRange.value,
      type: 2
    })

    // 添加返回值检查
    if (!res || !res.aggregated_data) {
      console.warn('趋势图数据返回格式不正确:', res);
      chartData.value = [];
      return;
    }

    // 确保aggregated_data是数组
    const aggregatedData = Array.isArray(res.aggregated_data) ? res.aggregated_data : [];

    chartData.value = aggregatedData
      .filter((item) => Array.isArray(item) && item.length > 0)
      .map(item => {
        let formatStr = 'YYYY-MM-DD'
        switch (chartTimeRange.value?.interval) {
          case 'day':
            formatStr = 'MM-DD'
            break
          case 'month':
            formatStr = 'YYYY-MM'
            break
          case 'year':
            formatStr = 'YYYY'
            break
          case 'quarter':
            formatStr = 'Q季度'
            break
        }

        // 检查item[0]是否存在
        if (!item[0] || !item[0].StartTime) {
          console.warn('趋势图时间数据不存在:', item);
          return null;
        }

        // 数值计算添加安全检查
        const value = item.reduce((acc, cur) => {
          // 确保cur.Used是有效的数字
          const usedValue = cur && typeof cur.Used !== 'undefined' ? Number(cur.Used) : 0;
          return acc + usedValue;
        }, 0).toFixed(2);

        return {
          time: dayjs(item[0].StartTime).format(formatStr),
          timestamp: dayjs(item[0].StartTime).valueOf(),
          value: value
        }
      })
      .filter(item => {
        return item !== null && item.timestamp !== -62135596800000
      })
      .sort((a, b) => a.timestamp - b.timestamp)
  } catch (error) {
    handleError(error, '获取趋势图数据失败')
    chartData.value = []
  } finally {
    trendChartLoading.value = false
  }
}

// 监听趋势图数据变化
watchEffect(getAreaData)

// 趋势图配置
const chartOptions = computed(() => ({
  xAxisData: chartData.value?.map(item => item.time) || [],
  yAxisUnit: 'kWh',
  series: [
    {
      name: '用电量',
      type: 'line',
      data: chartData.value?.map(item => item.value) || [],
    }
  ],
  customColors: ['#409EFF', '#909399']
}))

// 监听表格数据变化
watchEffect(async () => {
  if (tableDataRange.value && tableDataRange.value[0] && tableDataRange.value[1]) {
    tableLoading.value = true
    try {
      let tempAreaData = []
      let data = await getAreaTotalData(tableDataRange.value[0], tableDataRange.value[1], 'day')
      if (data && Array.isArray(data) && data.length > 0) {
        // 处理第一天的数据
        if (Array.isArray(data[0])) {
          data[0].forEach(item => {
            if (item && typeof item.area_id !== 'undefined' && typeof item.start_time !== 'undefined') {
              tempAreaData.push({
                area_id: item.area_id,
                [dayjs(item.start_time).format('YYYY/MM-DD')]: item.usage || 0
              });
            }
          });
        }

        // 处理剩余天数的数据
        for (let i = 1; i < data.length; i++) {
          if (Array.isArray(data[i])) {
            data[i].forEach(toPushArea => {
              if (toPushArea && typeof toPushArea.area_id !== 'undefined' && typeof toPushArea.start_time !== 'undefined') {
                let areaItem = tempAreaData.find(area => area.area_id === toPushArea.area_id);
                if (areaItem) {
                  areaItem[dayjs(toPushArea.start_time).format('YYYY/MM-DD')] = toPushArea.usage || 0;
                }
              }
            });
          }
        }
        areaData.value = tempAreaData
      } else {
        areaData.value = []
      }
    } catch (error) {
      handleError(error, '获取表格数据失败')
      areaData.value = []
    } finally {
      tableLoading.value = false
    }
  }
})
watch(PieChartData, () => {
  // 添加空值检查
  console.log('PieChartData change', PieChartData.value);

  if (PieChartData.value && PieChartData.value.length > 0) {
    selectedArea.value = PieChartData.value[0].area_id
  }
}, {
  immediate: true
})
// 计算表格日期并排序
const dates = computed(() => {
  if (!areaData.value || !areaData.value.length || !areaData.value[0]) return []

  // 获取所有日期列（排除 area_id）
  const allDates = Object.keys(areaData.value[0]).filter(key => key !== 'area_id')

  // 将所有日期统一格式并排序
  let sortedDates = allDates.sort((a, b) => {
    // 将 YYYY/MM-DD 转换为时间戳进行比较
    const timeA = dayjs(a.replace('/', '-')).valueOf()
    const timeB = dayjs(b.replace('/', '-')).valueOf()
    return timeA - timeB
  })
  return sortedDates
})

// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '';

  if (date.includes('/')) {
    return date
  }
  return date.replace('-', '/')
}

// 处理表格数据并按日期排序
const tableData = computed(() => {
  if (!areaData.value || !Array.isArray(areaData.value)) return [];

  let data = areaData.value.map(item => {
    if (!item) return null;

    const rowData = {
      district: areaStore.getAreaNameById(item.area_id) || `区域${item.area_id}`,
    }
    let sum = 0
    // 按照排序后的日期顺序添加数据
    if (dates.value && Array.isArray(dates.value)) {
      dates.value.forEach(date => {
        if (date) {
          const itemValue = item[date];
          rowData[date] = itemValue !== undefined && itemValue !== null ? Number(itemValue).toFixed(2) : '-';
          sum += +itemValue || 0;
        }
      });
    }
    rowData.sum = sum.toFixed(2)
    return rowData
  }).filter(item => item !== null);

  // 过滤掉所有日期用量都为0的行
  return data.filter(row => {
    return dates.value.some(date => {
      const val = Number(row[date]);
      return !isNaN(val) && val !== 0;
    });
  });
})

// 导出方法
const exportEvent = () => {
  const $table = tableRef.value
  if ($table) {
    $table.openExport({
      filename: "区域用电台账",
      type: "xlsx",
      exportMethod: ({ options }) => {
        return $table.exportData(
          Object.assign({}, options, {
            original: false,
            formatter: true,
            footer: true,
            columnFilterMethod: ({ column }) => {
              return column.property !== "seq"
            },
          })
        )
      },
    })
  }
}
</script>

<template>
  <div class="container">
    <div class="left">
      <div class="top">
        <el-card v-loading="pieChartLoading" class="chart-box" style="display: flex; flex-direction: column"
          body-style="flex: 1;">
          <template #header>
            <div class="card-header">
              <span>区域用电量</span>
              <CustomDateRadio @update:modelValue="pieChartTime = $event"></CustomDateRadio>
            </div>
          </template>
          <BasePieChart height="210px" :showLegend="false" :data="PieChartData" />
        </el-card>
        <el-card v-loading="trendChartLoading" class="chart-box" style="display: flex; flex-direction: column"
          body-style="flex: 1;">
          <template #header>
            <span>区域用电趋势</span>
            <div class="right-content">
              <el-select style="width: 35%;" filterable size="small" v-model="selectedArea">
                <el-option v-for="area in areaStore.areas" :key="area.id" :label="area.name"
                  :value="area.id"></el-option>
              </el-select>
              <CustomDateRadio :isFragmentation="true" @update:modelValue="chartTimeRange = $event">
              </CustomDateRadio>
            </div>
          </template>
          <BaseChart :options="chartOptions" />
        </el-card>
      </div>
      <div class="bottom">
        <el-card v-loading="tableLoading" class="table-box" body-style="flex:1;overflow:auto">
          <template #header>
            <div class="card-header">
              <div class="left-content">
                <span>区域用电台账</span>
                <CustomDatePicker v-model="tableDataRange" size="small" width="14rem"></CustomDatePicker>
              </div>
              <div class="right-content">
                <el-button type="primary" size="small" @click="exportEvent">
                  <template #icon>
                    <SvgIcon icon="download" />
                  </template>
                  导出
                </el-button>
              </div>
            </div>
          </template>
          <vxe-table v-if="!tableLoading" :export-config="{ type: 'xlsx', useStyle: true }" ref="tableRef" border
            :data="tableData" height="auto">
            <vxe-column fixed="left" field="district" title="区域" width="100" align="center" />
            <template v-for="date in dates" :key="date">
              <vxe-column :field="date" :title="formatDate(date)" width="120" align="center">
                <template #default="{ row }">
                  {{ row[date] }}
                </template>
              </vxe-column>
            </template>
            <vxe-column title="总计" width="120" align="center">
              <template #default="{ row }">
                {{ row.sum }}
              </template>
            </vxe-column>
          </vxe-table>
        </el-card>
      </div>
    </div>
    <div class="right">
      <el-card v-loading="rankingChartLoading" class="sidebar" body-style="flex:1">
        <template #header>
          <div class="card-header">
            <span>区域用电排名</span>
            <CustomDateRadio @update:modelValue="rankingChartTime = $event"></CustomDateRadio>
          </div>
        </template>
        <BaseRankingChart :horizontal="rankingHorizontal" title="区域用电排名" :data="RankingChartData"></BaseRankingChart>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  gap: var(--gap-normal);
  box-sizing: border-box;
}

.left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--gap-normal);
  min-width: 0;
}

.right {
  width: 400px;
  height: 100%;
  flex-shrink: 0;
}

.top {
  display: flex;
  gap: var(--gap-normal);
  height: 300px;
}

.chart-box {
  flex: 1;
  height: 100%;
  min-width: 0;
}

.bottom {
  flex: 1;
  min-height: 0;
}

.table-box {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-content {
  display: flex;
  align-items: center;
  gap: var(--gap-small);
}

.right-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
  gap: var(--gap-small);
}

@media (max-width: 1400px) {
  .container {
    flex-direction: column;
  }

  .left,
  .right {
    width: 100% !important;
    min-width: 0;
    height: auto;
  }

  .top {
    flex-direction: column;
    height: auto;
  }

  .chart-box {
    min-width: 0;
    height: 220px;
  }

  .sidebar {
    width: 100% !important;
    min-width: 0;
    height: auto;
  }

  .table-box {
    height: 500px;
  }
}
</style>